<template>
  <div class="hawkContent">
    <hawk-breadcrumb></hawk-breadcrumb>
    <el-row :gutter="20">
      <el-col :span="3">
        <el-input placeholder="输入触发器名称搜索" v-model="queryInfo.query.name">
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="hawkSearch" @click="init()">搜索</el-button>
        <el-button plain @click="clearSearchData()">重置</el-button>
      </el-col>
      <el-col :span="4"
              style="float: right;text-align: right;padding-right: 30px">
        <!-- <el-button type="primary" @click="syncTrigger">同步触发器</el-button> -->
        <el-button type="hawkCreate" @click="addRow()">创建触发器</el-button>
      </el-col>
    </el-row>

    <hawk-table :table-data="tableData" v-model="multipleSelection" :options="[
     { key: 'hostName', label: '主机名' },
      { key: 'nickName', label: '主机别名' },
        { key: 'itemName', label: '监控项' },
        { key: 'triggername', label: '触发器名称' },
        { key: 'conditions', label: '触发条件' },
        { key: 'threshold', label: '阈值' },
        { key: 'thresholdUnit', label: '单位' },
        { key: 'handle', label: '操作' },
      ]">

      <template #thresholdUnit="{ row }">
        <span> {{row.items.units}}</span>
      </template>

      <template #hostName="{ row }">
        <span> {{hostName}}</span>
      </template>

      <template #nickName="{ row }">
        <span> {{ nickName }} </span>
      </template>

      <template #itemName="{ row }">
        <span> {{row.items.name}}</span>
      </template>

      <!--      <template #threshold="{ row }">-->
      <!--        <span>{{row.threshold+row.thresholdUnit}}</span>-->
      <!--      </template>-->
      <template #handle="{ row }">
        <span class="hawk-text-btn" @click="editRow(row)">编辑</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="delRow(row)">删除</span>
      </template>
    </hawk-table>
    <!-- 分页/多选操作 -->
    <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">{{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click="batchDelete()">批量删除</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryInfo.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryInfo.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div>

    <!-- <div class="bottom-btns" style="float:right">

      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">{{ multipleSelection.length }} 选择</div>
        <el-button type="hawkDelete" @click="batchDelete()">批量删除</el-button>
      </div>

      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryInfo.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryInfo.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div> -->
    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="formTitle" :visible.sync="showEditForm" width="40%"
               :close-on-click-modal="false" @close="closeEditForm">
      <el-form :model="editData" :rules="editRules" ref="editRef"
               label-width="100px">
        <el-form-item label="名称" prop="triggername">
          <el-input v-model="editData.triggername" placeholder="请输入触发器名称">
          </el-input>
        </el-form-item>
        <el-form-item label="监控项" prop="itemid">
          <el-select clearable v-model="editData.itemid"
                     @change="changeTemplate" placeholder="请选择对应监控项">
            <el-option v-for="item in avlibileItemList" :key="item.hostId"
                       :label="item.name" :value="item.itemid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="触发条件" prop="conditions">
          <el-select clearable v-model="editData.conditions"
                     placeholder="请选择触发条件">
            <el-option label=">" value=">"></el-option>
            <el-option label="=" value="="></el-option>
            <el-option label="<" value="<"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阈值" prop="threshold">
          <el-input v-model="editData.threshold" placeholder="请输入阈值"
                    style="width:calc(80% - 5px);margin-right:5px"></el-input>
          <!-- <el-select clearable v-model="editData.unit" placeholder="请选择单位"
                     style="width:20%"> -->
          <!-- <el-option label="%" value="%"></el-option>
            <el-option label="KB" value="k"></el-option>
            <el-option label="MB" value="m"></el-option>
            <el-option label="GB" value="g"></el-option> -->
          <!-- </el-select> -->
          <el-input v-model="editData.unit" disabled style="width:20%" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditForm = false">取 消</el-button>
        <el-button type="primary" @click="saveData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getList, doAdd, getSellect, doEdit, doDelete, syncTrigger }
  from "@/api/monitor/config/host/trigger";
// import {syncItem} from "@/api/monitor/config/host/item";

import { getItemList }
  from '@/api/monitor/config/host/item'
import loginVue from '../../../login/login.vue';

/**
 * @author 创建者
 * @description 文件描述
 * @api 后台接口地址
 * @since 文件生成时间
 * @update 代码更新时间
 * @modifier 修改人
 * @bug bug名称或无
 * @version 版本号 例:v1.0.0
 */
export default {
  data () {
    return {
      tableData: [],
      // 提交信息
      queryInfo: {
        query: {
          name: '',
          type: '',
          hostId: ''
        },
        page: {
          current: 1,
          size: 10,
        },
      },
      // 数据总量
      total: 0,
      // 多选数据
      multipleSelection: [],
      // 显示添加/编辑
      showEditForm: false,
      // 添加编辑标题
      formTitle: '',
      // 添加编辑数据
      editData: {
        hostId: "",
        hostName: '',
        name: '',
        itemid: '',

        conditions: '', // 	条件
        threshold: '', // 	阈值
        triggerid: '', // 
        triggername: '', // 触发器名称
        unit: '', // 阈值单位
      },
      hostName: '',
      nickName: '',

      // 添加编辑验证
      editRules: {
        triggername: [{ required: true, message: '请输入触发器名称', trigger: 'blur' }],
        itemid: [{ required: true, message: '请选择对应监控项', trigger: 'blur' }],
        conditions: [{ required: true, message: '请选择触发条件', trigger: 'blur' }],
        threshold: [{ required: true, message: '请输入阈值并选择单位', trigger: 'blur' }],
      },
      // 监控项列表 , 所有的
      itemList: [],

      avlibileItemList: [], // 可用的监控项  =  所有的项， - 已用的项

      row: null, // 行数据
    };
  },

  async mounted () {
    this.row = this.$route.params.row
    this.queryInfo.query.hostId = this.row.hostid
    this.hostName = this.row.host
    this.nickName = this.row.name


    // 获得当前主机所有的 监控项
    let ret = await getItemList(this.queryInfo)
    console.log(ret, '---------当前主机，所有监控项');

    if (ret.code == 20000) {
      let data = ret.data
      this.itemList = data.records
    }

    this.init()



  },
  methods: {
    async init () {



      const ret = await getList(this.queryInfo);
      console.log(ret);
      if (ret.code == 20000) {

        let data = ret.data
        console.log(data, '--------获得所有触发器---');

        this.tableData = data.records.filter(el => el != null);
        this.parseAvItem()
      }

    },
    // 根据 总的 items 和 tableData 分析出，可用的 监控项列表
    parseAvItem () {

      this.avlibileItemList = this.itemList.filter(allItem => {
        console.log(111, allItem.itemid);
        let finds = this.tableData.find(obj => {
          console.log(222, obj.items.itemid);
          return obj.items.itemid == allItem.itemid
        })

        return finds == null

      })

      console.log(this.avlibileItemList, '---当前可用监控项-');

    },
    // 搜索
    search () {
      console.log(this.queryInfo);
    },
    // 重置搜索
    clearSearchData () {
      this.queryInfo = this.$options.data().queryInfo;
      this.queryInfo.query.hostId = this.row.hostid
      // this.queryInfo.query.type = this.routerParam.type;
      console.log(this.queryInfo);
      this.init()
    },
    // 新增
    addRow () {

      if (this.avlibileItemList.length == 0) {
        this.$msg({
          type: 'warn',
          message: '所有监控项都有触发器，不能再添加触发器'
        })
        return
      }

      console.log(this.hostName);
      this.editData.hostName = this.hostName;
      this.editData.hostId = this.row.hostid
      console.log(this.editData);
      this.showEditForm = true;
      this.formTitle = '新增触发器';
    },
    // 同步触发器数据
    // async syncTrigger(){
    //   this.$confirm('是否同步监控项？', '提示', {
    //     confirmButtonText: '是',
    //     cancelButtonText: '否'
    //   })
    //       .then(async () => {
    //         let  data  = await syncTrigger(this.queryInfo.query.hostId)
    //         this.$message({
    //           type: 'success',
    //           message: data.msg
    //         })
    //         this.init()
    //       })
    //       .catch(() => {})
    // },
    // 多选
    handleSelectionChange (val) {
      console.log(val)
      this.multipleSelection = val
    },
    // 编辑
    editRow (row) {


      console.log(row);
      this.formTitle = '编辑触发器';
      this.editData = Object.assign(this.editData, row);

      console.log(this.editData);

      let avItems = this.itemList.findIndex(item => {
        return item.itemid == this.editData.items.itemid
      })

      this.avlibileItemList.push(this.itemList[avItems])
      console.log(this.avlibileItemList);
      this.showEditForm = true;
    },
    // 新增/编辑提交
    saveData () {
      this.$refs.editRef.validate(async (valid) => {

        if (!valid) return
        console.log(this.editData);

        if (this.editData.triggerid) {

          let ret = await doEdit(this.editData);

          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.init();
        } else {

          let ret = await doAdd(this.editData);
          console.log(ret);

          if (ret.code == 20000) {

            this.$message({
              message: '添加成功',
              type: 'success'
            });

            this.init();
          }
        }
        this.showEditForm = false;
      })
    },
    changeTemplate (e) {
      this.itemList.map((item) => {
        if (item.itemid == e) {
          this.editData.items = item;
          this.editData.unit = item.units
        }
      });
    },

    // 批量删除
    async batchDelete () {
      if (this.multipleSelection.length < 1) {
        this.$message({
          type: 'warning',
          message: '请选择需要删除的数据',
        })
        return
      } else {
        let idList = []
        for (let i = 0; i < this.multipleSelection.length; i++) {
          idList.push(this.multipleSelection[i].triggerid)
        }
        console.log(idList)
        let ret = await doDelete(idList)
        console.log(ret)

        if (ret.code == 20000) {

          let type = ''
          if (ret.data || ret.message.indexOf('成功') != -1) {
            ret.message = '删除成功'
            type = 'success'
          } else {
            type = 'error'
          }

          this.$message({
            type: type,
            message: ret.message,
          })

        
          if (this.multipleSelection.length == this.tableData.length) {
            this.queryForm.page.current = this.queryForm.page.current - 1
            if (this.queryForm.page.current < 1) {
              this.queryForm.page.current = 1
            }
          }
          this.getHostList()

        }

      }


    },


    // 关闭添加/编辑弹窗
    closeEditForm () {
      this.editData = this.$options.data().editData;
      this.showEditForm = false;
      this.init()
    },
    // 删除
    delRow (row) {
      // if (!row.templateId) {
      this.$confirm('是否删除当前监控项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(async () => {
          const ret = await doDelete([row.triggerid])

           if (ret.code == 20000) {

            let type = ''
            if (ret.data || ret.message.indexOf('成功') != -1) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }
            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.tableData.length == 1) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            this.init()


          }



        })
        .catch(() => { })

      // } else {
      //   this.$message({
      //     message: '监控项未脱离模板时此触发器不可删除',
      //     type: 'warning'
      //   });
      // }
    },
    // 改变页码
    handleCurrentChange (val) {
      console.log(val)
    },
    // 改变数量
    handleSizeChange (val) {
      console.log(val)
    },
  }
}

</script>
<style lang='scss' scoped>
</style>